package cn.ydxiaoshuai.tools.task;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.ydxiaoshuai.tools.conts.JobConts;
import cn.ydxiaoshuai.tools.util.RedisUtil;
import cn.ydxiaoshuai.tools.vo.WXAccessToken;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 小帅丶
 * @className TaskUtil
 * @Description 定时任务
 * @Date 2020/6/17-16:12
 **/
@Component
@Slf4j
public class TaskUtil {
    @Autowired
    private RedisUtil redisUtil;
    /** 获取 ACCESS_TOKEN 接口地址 */
    public static String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=&secret=";
    /**
     * @Author 小帅丶
     * @Description 2小时执行一次获取token
     * @Date  2020/6/17 16:40
     * @return void
     **/
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void getAccessToken(){
        log.info("refreshAccessToken执行时间{}", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        String result = HttpUtil.get(GET_TOKEN_URL);
        log.info("{}-微信小程序获取AccessToken返回的内容:{}",DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN),result);
        WXAccessToken bean = JSON.parseObject(result,WXAccessToken.class);
        if(null!=bean.getAccess_token()){
            redisUtil.set(JobConts.WXAT_KEY,bean.getAccess_token());
        }else{
            redisUtil.set(JobConts.WXAT_KEY,"");
        }
    }
}
